package cn.lyjuan.android.demofive.ui.slide.section;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.lyjuan.android.demofive.R;
import cn.lyjuan.android.demofive.view.ViewHolder;
import cn.lyjuan.android.mylibrary.view.sectionlist.SectionedBaseAdapter;
import cn.lyjuan.base.util.PinyinUtils;
import cn.lyjuan.base.util.StringUtils;

/**
 * Created by chad on 04/11/2017.
 */

public class SectionAdapter extends SectionedBaseAdapter implements Filterable
{
    /**
     * 原始字符串
     */
    private List<String> strings;

    /**
     * 全部结构化数据
     */
    private List<SectionBean> originList;

    /**
     * 过滤后的结构化数据
     */
    private List<SectionBean> list = new ArrayList();

    /**
     * 上一次过滤数据，用于控制过滤数据
     */
    private String laestFilterChar;

    private Context context;

    private LayoutInflater lf;


    public SectionAdapter(Context context, List<String> strings)
    {
        this.context = context;
        lf = LayoutInflater.from(context);
        this.strings = strings;
        structuringData();
    }

    @Override
    public void notifyDataSetChanged()
    {
        list.clear();
        structuringData();// todo 重新结构化数据，可能会有性能问题
        super.notifyDataSetChanged();
    }

    /**
     * 将数据组装成 group形式
     */
    private void structuringData()
    {
        if (null == strings || strings.isEmpty())
            return;

        SectionBean bean = null;
        String[] pinyins = null;
        // 拼音、简写
        for (String s : strings)
        {
            if (null == s || s.trim().length() < 1) continue;

            pinyins = PinyinUtils.pinyinAndSimple(s);

            bean = createHaderOrExist(pinyins[1].substring(0, 1));
            bean.getItems().add(new SectionBean.SectionItem(s, pinyins[0], pinyins[1]));
        }
        if (null != bean)
            Collections.sort(bean.getItems());

        Collections.sort(list);
    }

    private SectionBean createHaderOrExist(String header)
    {
        for (SectionBean b : list)
        {
            if (header.equalsIgnoreCase(b.getHeader()))
                return b;
        }

        SectionBean bean = new SectionBean(header);
        bean.setItems(new ArrayList<SectionBean.SectionItem>());

        list.add(bean);

        return bean;
    }

    @Override
    public Filter getFilter()
    {
        return wordsFilter;
    }

    private Filter wordsFilter = new Filter()
    {
        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {
            String text = String.valueOf(constraint);
            // todo 执行过滤
            FilterResults result = new FilterResults();
            if (null == text || "".equals(text.trim()))
            {
                result.values = null == originList ? list : originList;
                result.count = null == originList ? list.size() : originList.size();
                return result;
            }

            text = text.toLowerCase();// 全小写

            List<SectionBean> newList = new ArrayList<>();
            List<SectionBean.SectionItem> itemList = null;

            List<SectionBean> filterList = null;// 需要过滤的数据
            if (StringUtils.isNull(laestFilterChar))// 之前未发生过滤
                filterList = list;
            else if (!StringUtils.isNull(laestFilterChar)
                    && text.startsWith(laestFilterChar))// 上一次有过滤，并且此次过滤是在上次的基础上增加过滤字符串
                filterList = list;
            else// 之前有过滤，并且关键词不匹配
                filterList = originList;
            for (SectionBean b : filterList)//循环分组
            {
                itemList = null;
                if (b.getItems().isEmpty()) continue;

                if (b.getHeader().equalsIgnoreCase(text))// 如果等于分组则直接添加整个分组信息
                {
                    newList.add(b);
                    continue;
                }

                for (SectionBean.SectionItem i : b.getItems())// 循环了项
                {
                    if (StringUtils.isNull(i.getContent()))
                        continue;

                    if (i.getContent().toLowerCase().contains(text)
                            || (!StringUtils.isNull(i.getPinyin()) && i.getPinyin().toLowerCase().contains(text))
                            || (!StringUtils.isNull(i.getPinyinSimple()) && i.getPinyinSimple().toLowerCase().contains(text)))
                    {
                        if (null == itemList)
                            itemList = new ArrayList<>();

                        itemList.add(i);
                    }
                }

                if (null != itemList)
                    newList.add(new SectionBean(b.getHeader(), itemList));
            }

            result.values = newList;
            result.count = newList.size();
            return result;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results)
        {
            if (null == originList)
                originList = list;

            laestFilterChar = String.valueOf(constraint);
            list = (List<SectionBean>) results.values;

            if (list.size() > 0)
                SectionAdapter.super.notifyDataSetChanged();// 本类中notifyDataSetChanged会结构化数据，但这里不用
            else
                SectionAdapter.super.notifyDataSetInvalidated();
        }
    };

    @Override
    public Object getItem(int section, int position)
    {
        return list.get(section).getItems().get(position);
    }

    @Override
    public long getItemId(int section, int position)

    {
        return 0;
    }

    @Override
    public int getCountForSection(int section)

    {
        return list.get(section).getItems().size();
    }

    @Override
    public int getSectionCount()
    {
        return list.size();
    }

    public Object getSection(int position)
    {
        return list.get(position);
    }

    /**
     * 根据section的排序计算出实际的位置
     *
     * @param section
     * @return
     */
    public int getSectionPostionForSection(int section)
    {
        int position = 0;
        for (int i = 0; i < section; i++)
        {
            position++;// 首先 section 位置加一
            position += list.get(i).getItems().size();// 加section的子项
        }

        return position;
    }

    @Override
    public View getItemView(int section, int position, View convertView, ViewGroup parent)
    {
        View view = ViewHolder.inflater(lf, convertView, R.layout.ui_slide_section_item);

        SectionBean.SectionItem data = (SectionBean.SectionItem) getItem(section, position);

        ((TextView) ViewHolder.get(view, R.id.section_title)).setText(data.getContent());


        return view;
    }

    @Override
    public View getSectionHeaderView(int section, View convertView, ViewGroup parent)
    {
        View view = ViewHolder.inflater(lf, convertView, R.layout.ui_slide_section_header);

        getItem(section);
        SectionBean data = list.get(section);

        ((TextView) ViewHolder.get(view, R.id.section_title)).setText(data.getHeader());
        return view;
    }
}
